package com.example.happ.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.happ.mapper.*;
import com.example.happ.pojo.*;
import com.example.happ.service.ReviewInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

@Service
public class ReviewInfoServImpl implements ReviewInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private StoreInfoMapper storeInfoMapper;
    @Resource
    private PriceInfoMapper priceInfoMapper;
    @Resource
    private ReviewInfoMapper reviewInfoMapper;
    @Resource
    private BlacklistInfoMapper blacklistInfoMapper;
    @Override
    public double countConsumeReviewById(int type, int id) {
        System.out.println("查询用户消耗金额与审核条数"+type+":"+id);
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("SUM(prize_amount) as sum")
                .eq("status", 2)
                .eq("store_id", id);

        // 根据 type 设置 updated_at 时间范围
        switch (type) {
            case 0: // 今天
                queryWrapper.ge("updated_at", LocalDate.now().atStartOfDay());
                break;
            case 1: // 昨天
                queryWrapper.ge("updated_at", LocalDate.now().minusDays(1).atStartOfDay())
                        .lt("updated_at", LocalDate.now().atStartOfDay());
                break;
            case 7: // 最近 7 天
                queryWrapper.ge("updated_at", LocalDate.now().minusDays(7).atStartOfDay());
                break;
            default: // 未知类型
                throw new IllegalArgumentException("Invalid type value: " + type);
        }
        List<Map<String, Object>> results = reviewInfoMapper.selectMaps(queryWrapper);
        System.out.println(results);
        if (results == null || results.isEmpty()|| results.get(0) == null) {
            System.out.println(results);
            return 0.00;
        }
        // 执行查询并返回结果
        return reviewInfoMapper.selectMaps(queryWrapper)
                .stream()
                .findFirst()
                .map(result -> {
                    Object sumValue = result.get("sum");
                    if (sumValue == null) {
                        return 0.00;
                    } else if (sumValue instanceof BigDecimal) {
                        return ((BigDecimal) sumValue).doubleValue();
                    } else if (sumValue instanceof Double) {
                        return (Double) sumValue;
                    } else {
                        throw new IllegalStateException("Unexpected type for sum: " + sumValue.getClass().getName());
                    }
                })
                .orElse(0.00);
    }
    @Override
    public long countValidReviewById(int type, int id) {
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 2);
        queryWrapper.eq("store_id", id);
        switch (type) {
            case 0:
                queryWrapper.ge("updated_at", LocalDate.now().atStartOfDay());
                break;
            case 1:
                queryWrapper.ge("updated_at", LocalDate.now().minusDays(1).atStartOfDay())
                        .lt("updated_at", LocalDate.now().atStartOfDay());
                break;
            case 7:
                queryWrapper.ge("updated_at", LocalDate.now().minusDays(7).atStartOfDay());
                break;
            default:
                throw new IllegalArgumentException("Invalid type value: " + type);
        }
        return reviewInfoMapper.selectCount(queryWrapper);
    }

    @Override
    public Boolean addAuditRecord(Map<String, String> requestBody) {
        System.out.println("添加评价记录表收到的数据："+requestBody);
        QueryWrapper<Store> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id", Integer.valueOf(requestBody.get("storeId")));
        Store store=storeInfoMapper.selectOne(queryWrapper2);
        System.out.println("门店设置一个用户只能提交几次："+store);
        QueryWrapper<Blacklist> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("user_id", Integer.valueOf(requestBody.get("id")))
                .eq("merchant_id", store.getMerchantId());
        Blacklist blacklist=blacklistInfoMapper.selectOne(queryWrapper4);
        if (blacklist != null) {
            return false;
        }
        QueryWrapper<Review> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("user_id", Integer.valueOf(requestBody.get("id")))
                .eq("store_id", Integer.valueOf(requestBody.get("storeId")))
                .eq("status", 1)
                .apply("DATE(created_at) = CURDATE()"); // 检查当天的记录
        Long count = reviewInfoMapper.selectCount(queryWrapper3);
        System.out.println("用户已经提交过几次："+count);
        if (count >= store.getSubmit()) {
            return false;
        }
        Review review = new Review();
        review.setUserId(Integer.valueOf(requestBody.get("id")));
        review.setStoreId(Integer.valueOf(requestBody.get("storeId")));
        review.setScreen(requestBody.get("screen"));
        review.setScreenshot(requestBody.get("screenshot"));
        review.setStatus(1);
        review.setPrizeId(1);
        QueryWrapper<Price> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",1);
        Price price=priceInfoMapper.selectOne(queryWrapper);
        double random= Math.random()*(price.getMaxAmount()-price.getMinAmount()+1)+price.getMinAmount();
        review.setPrizeAmount(random);
        review.setReviewedBy(Integer.valueOf(requestBody.get("status")));
        review.setCreatedAt(new Date());
        review.setPlatformName(requestBody.get("platform"));
        System.out.println(review);
        return reviewInfoMapper.insert(review)>0?true:false;
    }

    @Override
    public ReviewMain getAuditRecord(Map<String, String> requestBody) {
        QueryWrapper<Review> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id", Integer.valueOf(requestBody.get("id")));
        Review review=reviewInfoMapper.selectOne(queryWrapper1);
        System.out.println(review);

        QueryWrapper<Price> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", review.getPrizeId());
        Price price=priceInfoMapper.selectOne(queryWrapper);

        QueryWrapper<Store> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id", review.getStoreId());
        Store store=storeInfoMapper.selectOne(queryWrapper2);

        QueryWrapper<User> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("id", review.getUserId());
        User user=userInfoMapper.selectOne(queryWrapper3);

        Date originalCreateTime = review.getCreatedAt();
        System.out.println(store);
        // 添加 12 小时
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(originalCreateTime);
        calendar.add(Calendar.HOUR, store.getReviewedAt());
        Date now=calendar.getTime();

        ReviewMain reviewMain=new ReviewMain(review,store,price,user,now);
        return reviewMain;
    }

    @Override
    public boolean changeAuditStatus(Integer id, Integer status) {
        Review review = new Review();
        review.setStatus(status);
        review.setUpdatedAt(new Date());
        UpdateWrapper<Review> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        return reviewInfoMapper.update(review,updateWrapper)!=0?true:false;
    }

    @Override
    public Map<String, Object> getAuditRecordAll(Map<String, String> requestBody) {
        System.out.println("待审核列表请求收到的数据:"+requestBody);
        int page = Integer.parseInt(requestBody.get("page"));
        int size = Integer.parseInt(requestBody.get("size"));
        Page<Review> pageRequest = new Page<>(page, size);
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", requestBody.get("storeId"))
                .eq("status",1);
        Page<Review> pageResult = reviewInfoMapper.selectPage(pageRequest, queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("data", pageResult.getRecords());     // 当前页数据
        result.put("total", pageResult.getTotal());      // 总记录数
        result.put("currentPage", pageResult.getCurrent()); // 当前页码
        result.put("pageSize", pageResult.getSize());
        System.out.println("待审核列表请求返回的数据:"+result);
        return result;
    }

    @Override
    public Map<String, Object> selectAuditRecordAll(Map<String, String> requestBody) {
        QueryWrapper queryWrapper1 =new QueryWrapper<>();
        queryWrapper1.eq("merchant_id",requestBody.get("merchantId"));
        System.out.println("查到店铺信息："+storeInfoMapper.selectOne(queryWrapper1));
        int storeId = storeInfoMapper.selectOne(queryWrapper1).getId();
        System.out.println("审核列表请求收到的数据:"+requestBody);
        int page = Integer.parseInt(requestBody.get("page"));
        int size = Integer.parseInt(requestBody.get("size"));
        Page<Review> pageRequest = new Page<>(page, size);
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        Page<Review> pageResult = reviewInfoMapper.selectPage(pageRequest, queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("data", pageResult.getRecords());     // 当前页数据
        result.put("total", pageResult.getTotal());      // 总记录数
        result.put("currentPage", pageResult.getCurrent()); // 当前页码
        result.put("pageSize", pageResult.getSize());
        System.out.println("审核列表请求返回的数据:"+result);
        return result;
    }
}
